package com.henry.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import sun.misc.BASE64Decoder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Henry
 * @date 2020/6/21 11:22
 */
public class HttpBasicAuthorizeAttribute implements Filter {

    private BASE64Decoder base64Decoder = new BASE64Decoder();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String auth = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
        boolean b = doHttpBasicAuthorize(auth);
        if(b){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "authrize failed");
            httpResponse.getWriter().write(jsonObject.toJSONString());
        }

    }

    @Override
    public void destroy() {

    }

    private boolean doHttpBasicAuthorize(String auth){
//        boolean result=false;
        try {
            if (auth != null && auth.length()>6) {
                auth = auth.substring(6);
                byte[] bytes = base64Decoder.decodeBuffer(auth);
                String decodedAuth = new String(bytes);
                String[] userArray = decodedAuth.split(":",2);
                if(userArray!=null&&userArray.length==2){
                    return checkData(userArray[0], userArray[1]);
                }

            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

    private boolean checkData(String name, String password) {
        return "henry".equals(name) && "123".equals(password);
    }
}
